/**
 * 文件传输页面脚本
 */

const { ipcRenderer } = require('electron');
const path = require('path');

// ==================== 全局变量 ====================
let currentLocalPath = '';
let currentRemotePath = '/';
let transferTasks = [];
let currentTypeFilter = 'all'; // all, upload, download
let currentStatusFilter = 'all'; // all, active, completed, failed
let isWindowsOS = process.platform === 'win32'; // 检测是否为 Windows 系统
const MY_COMPUTER = '__MY_COMPUTER__'; // 特殊标识：磁盘列表视图

// ==================== DOM元素 ====================
const localPath = document.getElementById('localPath');
const localUpBtn = document.getElementById('localUpBtn');
const localRefreshBtn = document.getElementById('localRefreshBtn');
const localHomeBtn = document.getElementById('localHomeBtn');
const localFiles = document.getElementById('localFiles');

const remotePath = document.getElementById('remotePath');
const remoteUpBtn = document.getElementById('remoteUpBtn');
const remoteRefreshBtn = document.getElementById('remoteRefreshBtn');
const remoteHomeBtn = document.getElementById('remoteHomeBtn');
const remoteFiles = document.getElementById('remoteFiles');

const transferList = document.getElementById('transferList');
const queueStats = document.getElementById('queueStats');
const pauseAllBtn = document.getElementById('pauseAllBtn');
const resumeAllBtn = document.getElementById('resumeAllBtn');
const cancelAllBtn = document.getElementById('cancelAllBtn');
const clearCompletedBtn = document.getElementById('clearCompletedBtn');

// ==================== 本地文件操作 ====================
async function loadLocalFiles(dirPath) {
  try {
    console.log('加载本地文件:', dirPath);
    
    // 特殊处理：显示磁盘列表
    if (dirPath === MY_COMPUTER) {
      showDrivesList();
      return;
    }
    
    currentLocalPath = dirPath;
    localPath.value = dirPath === MY_COMPUTER ? '此电脑' : dirPath;
    
    localFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">⏳</div><div>加载中...</div></div>';
    
    const items = await ipcRenderer.invoke('read-directory', dirPath);
    
    if (!items || items.length === 0) {
      localFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">📁</div><div>文件夹为空</div></div>';
      return;
    }
    
    renderLocalFiles(items);
  } catch (error) {
    console.error('加载本地文件失败:', error);
    localFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">❌</div><div>加载失败: ' + error.message + '</div></div>';
  }
}

// 显示磁盘列表（Windows）
async function showDrivesList() {
  console.log('显示磁盘列表');
  currentLocalPath = MY_COMPUTER;
  localPath.value = '💻 此电脑';
  
  localFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">⏳</div><div>正在检测磁盘...</div></div>';
  
  try {
    // 从主进程获取实际可用的磁盘列表
    const drives = await ipcRenderer.invoke('get-available-drives');
    
    console.log('检测到的可用磁盘:', drives);
    
    if (!drives || drives.length === 0) {
      localFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">💾</div><div>未检测到可用磁盘</div></div>';
      return;
    }
    
    const html = drives.map(drive => {
      return `
        <div class="file-item" data-path="${drive}" data-is-dir="true">
          <div class="file-name">
            <span class="file-icon">📁</span>
            <span class="file-name-text" ondblclick="handleDriveClick('${drive}')">本地磁盘 (${drive})</span>
          </div>
          <div class="file-size">-</div>
          <div class="file-modified">-</div>
          <div class="file-actions">
          </div>
        </div>
      `;
    }).join('');
    
    localFiles.innerHTML = html;
  } catch (error) {
    console.error('获取磁盘列表失败:', error);
    localFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">❌</div><div>获取磁盘列表失败</div></div>';
  }
}

// 处理磁盘点击
function handleDriveClick(drive) {
  console.log('点击磁盘:', drive);
  const drivePath = drive + '\\';
  loadLocalFiles(drivePath);
}

// 暴露到全局作用域
window.handleDriveClick = handleDriveClick;

function renderLocalFiles(items) {
  const html = items.map(item => {
    const icon = item.isDirectory ? '📁' : getFileIcon(item.name);
    const size = item.isDirectory ? '-' : formatFileSize(item.size);
    const time = formatDate(item.modifiedTime);
    
    return `
      <div class="file-item" data-path="${path.join(currentLocalPath, item.name)}" data-is-dir="${item.isDirectory}">
        <div class="file-name">
          <span class="file-icon">${icon}</span>
          <span class="file-name-text" ondblclick="handleLocalFileDoubleClick('${item.name}', ${item.isDirectory})">${item.name}</span>
        </div>
        <div class="file-size">${size}</div>
        <div class="file-modified">${time}</div>
        <div class="file-actions">
          ${!item.isDirectory ? `<button class="btn-action" onclick="uploadFile('${item.name}')">⬆️ 上传</button>` : `<button class="btn-action" onclick="uploadFolder('${item.name}')">⬆️ 上传文件夹</button>`}
        </div>
      </div>
    `;
  }).join('');
  
  localFiles.innerHTML = html;
}

function handleLocalFileDoubleClick(fileName, isDirectory) {
  if (isDirectory) {
    const newPath = path.join(currentLocalPath, fileName);
    loadLocalFiles(newPath);
  }
}

// 选择本地目录按钮
const localChooseDirBtn = document.getElementById('localChooseDirBtn');
localChooseDirBtn.addEventListener('click', async () => {
  console.log('选择本地目录');
  try {
    const selectedPath = await ipcRenderer.invoke('open-directory-dialog');
    if (selectedPath) {
      console.log('用户选择了目录:', selectedPath);
      loadLocalFiles(selectedPath);
    }
  } catch (error) {
    console.error('选择目录失败:', error);
  }
});

localUpBtn.addEventListener('click', () => {
  console.log('返回上一级');
  
  // 如果当前在磁盘列表，无法再往上
  if (currentLocalPath === MY_COMPUTER) {
    console.log('已经在顶级目录');
    return;
  }
  
  // Windows 系统：检查是否在磁盘根目录
  if (isWindowsOS) {
    // 判断是否为磁盘根目录 (如 C:\, D:\ 等)
    if (currentLocalPath.match(/^[A-Z]:\\?$/i)) {
      console.log('在磁盘根目录，显示磁盘列表');
      loadLocalFiles(MY_COMPUTER);
      return;
    }
  }
  
  const parentPath = path.dirname(currentLocalPath);
  if (parentPath !== currentLocalPath) {
    loadLocalFiles(parentPath);
  } else if (isWindowsOS) {
    // 已经到达顶层，显示磁盘列表
    loadLocalFiles(MY_COMPUTER);
  }
});

localRefreshBtn.addEventListener('click', () => {
  console.log('刷新本地文件');
  loadLocalFiles(currentLocalPath);
});

localHomeBtn.addEventListener('click', async () => {
  console.log('返回主目录');
  const homePath = await ipcRenderer.invoke('get-home-path');
  loadLocalFiles(homePath);
});

// ==================== 远程文件操作 ====================
async function loadRemoteFiles(dirPath) {
  try {
    console.log('加载远程文件:', dirPath);
    currentRemotePath = dirPath;
    remotePath.value = dirPath;
    
    remoteFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">⏳</div><div>加载中...</div></div>';
    
    const result = await ipcRenderer.invoke('remote-list', dirPath);
    
    if (!result || !result.files || result.files.length === 0) {
      remoteFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">☁️</div><div>文件夹为空</div></div>';
      return;
    }
    
    renderRemoteFiles(result.files);
  } catch (error) {
    console.error('加载远程文件失败:', error);
    remoteFiles.innerHTML = '<div class="empty-state"><div class="empty-state-icon">❌</div><div>加载失败: ' + error.message + '</div></div>';
  }
}

function renderRemoteFiles(files) {
  const html = files.map(file => {
    const icon = file.isDirectory ? '📁' : getFileIcon(file.name);
    const size = file.isDirectory ? '-' : formatFileSize(file.size);
    const time = formatDate(file.uploadTime);
    
    return `
      <div class="file-item" data-id="${file.id}" data-is-dir="${file.isDirectory}">
        <div class="file-name">
          <span class="file-icon">${icon}</span>
          <span class="file-name-text" ondblclick="handleRemoteFileDoubleClick('${file.id}', '${file.name}', ${file.isDirectory})">${file.name}</span>
        </div>
        <div class="file-size">${size}</div>
        <div class="file-modified">${time}</div>
        <div class="file-actions">
          ${!file.isDirectory ? `<button class="btn-action" onclick="downloadFile('${file.id}', '${file.name}', ${file.size})">⬇️ 下载</button>` : ''}
          <button class="btn-action btn-danger" onclick="deleteRemoteFile('${file.id}', '${file.name}')">🗑️</button>
        </div>
      </div>
    `;
  }).join('');
  
  remoteFiles.innerHTML = html;
}

function handleRemoteFileDoubleClick(fileId, fileName, isDirectory) {
  if (isDirectory) {
    const newPath = currentRemotePath === '/' ? `/${fileName}` : `${currentRemotePath}/${fileName}`;
    loadRemoteFiles(newPath);
  }
}

remoteUpBtn.addEventListener('click', () => {
  console.log('返回上一级');
  if (currentRemotePath !== '/') {
    const parts = currentRemotePath.split('/').filter(p => p);
    parts.pop();
    const parentPath = parts.length > 0 ? '/' + parts.join('/') : '/';
    loadRemoteFiles(parentPath);
  }
});

remoteRefreshBtn.addEventListener('click', () => {
  console.log('刷新远程文件');
  loadRemoteFiles(currentRemotePath);
});

remoteHomeBtn.addEventListener('click', () => {
  console.log('返回根目录');
  loadRemoteFiles('/');
});

// ==================== 传输任务管理 ====================
function updateQueueStats() {
  const total = transferTasks.length;
  const active = transferTasks.filter(t => t.status === 'active' || t.status === 'uploading' || t.status === 'downloading').length;
  const completed = transferTasks.filter(t => t.status === 'completed').length;
  
  queueStats.textContent = `总计: ${total} | 进行中: ${active} | 已完成: ${completed}`;
}

function renderTransferTasks() {
  // 过滤任务
  let filteredTasks = transferTasks;
  
  if (currentTypeFilter !== 'all') {
    filteredTasks = filteredTasks.filter(t => t.type === currentTypeFilter);
  }
  
  if (currentStatusFilter !== 'all') {
    filteredTasks = filteredTasks.filter(t => t.status === currentStatusFilter);
  }
  
  // 渲染任务
  if (filteredTasks.length === 0) {
    transferList.innerHTML = '<div class="empty-state"><div class="empty-state-icon">📋</div><div>暂无传输任务</div></div>';
    return;
  }
  
  transferList.innerHTML = filteredTasks.map(task => `
    <div class="transfer-task" data-id="${task.id}">
      <div class="task-header">
        <div class="task-name">${task.type === 'upload' ? '<img src="./assets/upload.svg" alt="上传" style="width: 16px; height: 16px; vertical-align: middle;">' : '<img src="./assets/dow.svg" alt="下载" style="width: 16px; height: 16px; vertical-align: middle;">'} ${task.name}</div>
        <div class="task-actions">
          <button class="task-btn" onclick="pauseTask('${task.id}')">⏸️</button>
          <button class="task-btn" onclick="cancelTask('${task.id}')">⏹️</button>
        </div>
      </div>
      <div class="task-progress">
        <div class="progress-bar">
          <div class="progress-fill ${task.status}" style="width: ${task.progress}%"></div>
        </div>
        <div class="task-info">
          <span>${task.progress}% (${task.transferred} / ${task.total})</span>
          <span class="task-speed">${task.speed || '0 B/s'}</span>
        </div>
      </div>
    </div>
  `).join('');
}

// 队列操作按钮
pauseAllBtn.addEventListener('click', () => {
  console.log('暂停所有任务');
  // TODO: 实现暂停所有任务逻辑
});

resumeAllBtn.addEventListener('click', () => {
  console.log('继续所有任务');
  // TODO: 实现继续所有任务逻辑
});

cancelAllBtn.addEventListener('click', () => {
  console.log('取消所有任务');
  if (confirm('确定要取消所有传输任务吗？')) {
    // TODO: 实现取消所有任务逻辑
  }
});

clearCompletedBtn.addEventListener('click', () => {
  console.log('清除已完成任务');
  transferTasks = transferTasks.filter(t => t.status !== 'completed');
  renderTransferTasks();
  updateQueueStats();
});

// ==================== 过滤器 ====================
const typeFilterTabs = document.querySelectorAll('#typeFilter .filter-tab');
typeFilterTabs.forEach(tab => {
  tab.addEventListener('click', () => {
    typeFilterTabs.forEach(t => t.classList.remove('active'));
    tab.classList.add('active');
    currentTypeFilter = tab.getAttribute('data-type');
    renderTransferTasks();
  });
});

const statusFilterTabs = document.querySelectorAll('#statusFilter .filter-tab');
statusFilterTabs.forEach(tab => {
  tab.addEventListener('click', () => {
    statusFilterTabs.forEach(t => t.classList.remove('active'));
    tab.classList.add('active');
    currentStatusFilter = tab.getAttribute('data-status');
    renderTransferTasks();
  });
});

// ==================== 任务操作函数 ====================
function pauseTask(taskId) {
  console.log('暂停任务:', taskId);
  // TODO: 实现暂停任务逻辑
}

function cancelTask(taskId) {
  console.log('取消任务:', taskId);
  if (confirm('确定要取消这个传输任务吗？')) {
    // TODO: 实现取消任务逻辑
  }
}

// ==================== 辅助函数 ====================
function getFileIcon(fileName) {
  const ext = fileName.split('.').pop().toLowerCase();
  const iconMap = {
    'pdf': '📄',
    'doc': '📝', 'docx': '📝',
    'xls': '📊', 'xlsx': '📊',
    'ppt': '📊', 'pptx': '📊',
    'zip': '📦', 'rar': '📦', '7z': '📦',
    'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️',
    'mp4': '🎬', 'avi': '🎬', 'mkv': '🎬',
    'mp3': '🎵', 'wav': '🎵',
    'txt': '📃',
    'js': '📜', 'json': '📜', 'html': '📜', 'css': '📜'
  };
  return iconMap[ext] || '📄';
}

function formatFileSize(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}

function formatDate(dateString) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

function uploadFile(fileName) {
  const localFilePath = path.join(currentLocalPath, fileName);
  console.log('上传文件:', localFilePath, '到', currentRemotePath);
  // TODO: 调用IPC上传文件
  alert('上传功能开发中...');
}

function uploadFolder(folderName) {
  const localFolderPath = path.join(currentLocalPath, folderName);
  console.log('上传文件夹:', localFolderPath, '到', currentRemotePath);
  // TODO: 调用IPC上传文件夹
  alert('上传文件夹功能开发中...');
}

function downloadFile(fileId, fileName, fileSize) {
  console.log('下载文件:', fileId, fileName);
  // TODO: 调用IPC下载文件
  alert('下载功能开发中...');
}

function deleteRemoteFile(fileId, fileName) {
  if (confirm(`确定要删除 ${fileName} 吗？`)) {
    console.log('删除远程文件:', fileId);
    // TODO: 调用IPC删除文件
    alert('删除功能开发中...');
  }
}

// ==================== 初始化 ====================
async function initialize() {
  console.log('文件传输页面初始化...');
  
  // 加载本地文件（获取用户主目录）
  try {
    const homePath = await ipcRenderer.invoke('get-home-path');
    await loadLocalFiles(homePath);
  } catch (error) {
    console.error('加载本地文件失败:', error);
  }
  
  // 加载远程文件
  try {
    await loadRemoteFiles('/');
  } catch (error) {
    console.error('加载远程文件失败:', error);
  }
  
  // 渲染传输任务
  renderTransferTasks();
  updateQueueStats();
  
  console.log('文件传输页面初始化完成');
}

// 页面加载时初始化
window.addEventListener('DOMContentLoaded', initialize);
